﻿using Dyao.Book.Contract;
using Dyao.Book.Entity;
using Dyao.Repository.Abstractions;

namespace Dyao.Book.Repository
{
    using Foundation.Replacement;

    public class TaskCenterRuleRepository : DataRepository<TaskCenterRuleEntity, int>, ITaskCenterRuleRepository
    {
        /// <summary>
        /// 获取任务中心规则列表
        /// </summary>
        /// <param name="idList">idList</param>
        /// <param name="cancellationToken">cancellationToken</param>
        /// <returns></returns>
        public async Task<List<TaskCenterRuleDto>> GetTaskCenterRuleListAsync(List<int> idList, CancellationToken cancellationToken = default)
        {
            var queryable = GetQueryable().Where(m => idList.Contains(m.ID)).OrderBy(m => m.ID);
            var queryableModel = queryable.Select(m => new TaskCenterRuleDto
            {
                Id = m.ID,
                RuleKey = m.RuleKey,
                Name = m.Name,
                RuleSettings = m.RuleSettings
            });
            var taskCenterRuleModelList = await queryableModel.ToListAsync(cancellationToken);
            return taskCenterRuleModelList;
        }

        #region  // override methods

        public override async Task<TaskCenterRuleEntity> InsertAsync(TaskCenterRuleEntity entity, bool autoSave = false, CancellationToken cancellationToken = default)
        {
            CompletedAppKey(entity);

            return await base.InsertAsync(entity, autoSave, cancellationToken);
        }

        public override async Task InsertRangeAsync(IEnumerable<TaskCenterRuleEntity> entities, bool autoSave = false, CancellationToken cancellationToken = default)
        {
            foreach (var entity in entities)
            {
                CompletedAppKey(entity);
            }

            await base.InsertRangeAsync(entities, autoSave, cancellationToken);
        }

        protected void CompletedAppKey(TaskCenterRuleEntity entity)
        {
            if (string.IsNullOrWhiteSpace(entity.AppKey))
            {
                entity.AppKey = "DyaoBook";
            }
        }

        #endregion //end override methods
    }
}
